package cn.yl.fxboot.application.action.handler;

import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.Executor;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.yl.fxboot.application.action.MsgPaneActions;
import cn.yl.fxboot.application.common.utils.SpringUtils;
import cn.yl.fxboot.application.service.DecodeVideo;
import cn.yl.fxboot.application.service.DouyinHelper;
import cn.yl.fxboot.application.service.Script;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableMap;
import javafx.concurrent.Task;
import javafx.concurrent.Worker;
import javafx.concurrent.Worker.State;
import javafx.event.EventHandler;
import javafx.scene.control.TextField;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;

public class WebViewHandler {

	public static WebView initWebView(WebView authorView_WV,TextField authorAddr_TF,String taskId,ObservableMap<String,Object> obMap) {
		StringBuilder nickName  = new StringBuilder();
		
		WebEngine we = authorView_WV.getEngine();
		Worker<Void> wk = we.getLoadWorker();
		wk.stateProperty().addListener(new ChangeListener<State>() {
			@Override
			public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
				if(State.SUCCEEDED.equals(newValue)) {
					HashMap<String,String> script= Script.getScript(we,0L);
					if(script != null && script.containsKey("script")) {
						we.executeScript(script.get("script"));
						nickName.delete(0, nickName.length());
						nickName.append(script.get("nickName"));
					}else {
						obMap.put("totalUrl", (Long)obMap.get("totalUrl") -1);
					}
				}
			}
		});
		
		we.setOnAlert(new EventHandler<WebEvent<String>>() {
			@Override
			public void handle(WebEvent<String> event) {
				JSONObject json = JSONUtil.parseObj(event.getData());
				if(json.getBool("has_more")) {
					try {
						HashMap<String,String> script = Script.getScript(we,json.getLong("max_cursor"));
						we.executeScript(script.get("script"));
					}catch(Exception e) {
						obMap.put("totalUrl", (Long)obMap.get("totalUrl") -1);
					}
				}
				
				//此處處理視頻數據
				JSONArray array = json.getJSONArray("aweme_list");
				String output = authorAddr_TF.getText() + "\\" + nickName.toString();
				int total = array.size();
				synchronized (obMap) {
					obMap.put("total", (Long)obMap.get("total") + total);
					obMap.put("count", (Integer)obMap.get("count") + total);
				}
				for(Object j : array) {
					JSONObject obj = JSONUtil.parseObj(j);
					String title = (String) obj.getByPath("desc");
					String url = (String) obj.getByPath("video.play_addr.url_list[0]");
					String avatar = (String) obj.getByPath("author.avatar_thumb.url_list[0]");
					String nickname =	(String) obj.getByPath("author.nickname");
					String cover = (String)obj.getByPath("video.cover.url_list[0]");
					DecodeVideo dv = new DecodeVideo();
					dv.setTitle(title.replace("@抖音小助手", ""));
					dv.setPlayAddr(url);//(Common.getLocationUrl(url));
					dv.setAvatar(avatar);
					dv.setAuthor(nickname);
					dv.setCoverPicture(cover);
					dv.setTime(new Date());
					String subTaskId = taskId+"子任务 " + RandomUtil.randomString(4) + " --> ";
					Task<Void> task = new Task<Void>() {
						@Override
						protected void cancelled() {
							updateMessage("error:被中断!");
						}
						@Override
						protected void failed() {
							updateMessage("error:失败!");
						}
						@Override
						protected Void call() throws Exception {
							MsgPaneActions.doLog(subTaskId + "正在下載:"+nickName+"的"+title );
							String res = DouyinHelper.downloadOnlyVideo(dv, output);
							//String res = "test";
							if(res != null) {
								MsgPaneActions.doLog( subTaskId + "完成:  " + res);
								obMap.put("count", (Integer)obMap.get("count") - 1);
							}
							return null;
						}
					};
					task.messageProperty().addListener(new ChangeListener<String>() {
						@Override
						public void changed(ObservableValue<? extends String> observable, String oldValue,
								String newValue) {
							MsgPaneActions.doLog(subTaskId + newValue);
						}
					});
					Executor pool =  (Executor) SpringUtils.getBean("customServiceExecutor"); 
					pool.execute(task);
				}
			}
		});
		return authorView_WV;
	}
}
